package cn._51doit.flink.day01;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

/**
 *
 * 使用自定义Sink，实现与print Sink 一样的功能
 *
 */
public class MyPrintSink {

    public static void main(String[] args) throws Exception {

        //在本地执行，执行环境的默认并行度为：当前机器cpu的逻辑核数据（cpu线程数）
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 8081);
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
        //env.setParallelism(8);

        //活动当前执行环境的默认并行度
        int parallelism = env.getParallelism();
        System.out.println("当前执行环境的并行度为：" + parallelism);

        //获取算子所在task的并行度(就是获取对应DataStream的并行度)
        //SocketSource即调用socketTextStream创建的DataStream并行度永远为1
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);
        int parallelism1 = lines.getParallelism();
        System.out.println("SocketSource对应DataStream的并行为：" + parallelism1);

        //map是多并行的算子，如果没有任务指定该算子的并行度，默认与执行环境的并行度保持一致
        SingleOutputStreamOperator<String> upperStream = lines.map(new MapFunction<String, String>() {
            @Override
            public String map(String line) throws Exception {
                return line.toUpperCase();
            }
        }).setParallelism(2);

        //获取map算子对应Task的并行度
        int parallelism2 = upperStream.getParallelism();
        System.out.println("map算子所在Task的并行度：" + parallelism2);

        //调用sink
        DataStreamSink<String> streamSink = upperStream.addSink(new RichSinkFunction<String>() {
            @Override
            public void invoke(String value, Context context) throws Exception {
                //sink每来一条数据，会调用一次invoke方法
                //获取当前subtask的index，然后将index + 1
                //getRuntimeContext可以获取当前正在运行的subtask的很多信息
                int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
                System.out.println(indexOfThisSubtask + " > " + value);
            }
        });


        int parallelism3 = streamSink.getTransformation().getParallelism();
        System.out.println("Sink算子所在Task的并行度: " + parallelism3);

        env.execute();

    }
}
